package com.jajahome.diyview;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.view.View;

import java.io.ByteArrayOutputStream;

/**
 * 图像镜像操作
 */
public class BitmapUtil {

    /**
     * 镜像水平翻转 大小不变
     *
     * @param a ：要反转的bitmap
     * @return 已经反转的bitmap
     */
    public static Bitmap convert(Bitmap a) {
        if(a == null){
            return  a;
        }
        int w = a.getWidth();
        int h = a.getHeight();
        Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
        Canvas cv = new Canvas(newb);
        Matrix m = new Matrix();
        m.postScale(-1, 1);   //镜像水平翻转
        Bitmap new2 = Bitmap.createBitmap(a, 0, 0, w, h, m, true);
        cv.drawBitmap(new2, new Rect(0, 0, new2.getWidth(), new2.getHeight()), new Rect(0, 0, w, h), null);
        a.recycle();
        return newb;
    }

    /**
     * Bitmap转换成byte[]并且进行压缩,压缩到不大于maxkb
     *
     * @return
     */
    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        byte[] result = new byte[0];
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, output);
            int options = 100;
            while (output.toByteArray().length /1024> 32&& options != 0) {
                output.reset(); //清空output
                bmp.compress(Bitmap.CompressFormat.JPEG, options, output);//这里压缩options%，把压缩后的数据存放到output中
                options -= 10;

            }
            result = output.toByteArray();
            if (needRecycle) {
                bmp.recycle();
            }
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
